package org.twndmv.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twndmv.bo.Person;
import org.twndmv.dao.PersonDAO;

public class PersonDAOImpl implements PersonDAO {

	private static Log log = LogFactory.getLog(PersonDAOImpl.class);
	private EntityManager em;
	
	public PersonDAOImpl() {
	}
	
	public PersonDAOImpl(EntityManager eman) {
		this.em = eman;
	}
	
	/**
	 * Normal find method.  Could not get em.find to return null when person wasnt supposed to be here so used
	 * this method instead.
	 */
	@Override
	public Person getPersonByID(long id) {
//		Query query = em.createQuery("Select a from Person as a where id = " + id);
		Person results = null;
		results = em.find(Person.class,id);
//		try {
//		 results = (Person)query.getSingleResult();
//		} catch (NoResultException nre) {
//		  log.warn("No person found with id = " + id);	
//		} catch (NonUniqueResultException nure) {
//			log.warn("Two or more people have the same id = " + id);
//		}
		return results;
	}

	@Override
	public List<Person> getPersonByLastName(String name) {
		Query query = em.createQuery("Select a from Person as a where LASTNAME = '" + name + "'");
		List<Person> resultPeople = new ArrayList<Person>();
		for(Object entry : query.getResultList()) {
			Person results = (Person)entry;
			resultPeople.add(results);
		}
		return resultPeople;
	}

	@Override
	public void createPerson(Person newPerson) {
		em.persist(newPerson);
		log.debug("person created:" + newPerson);
		
//		em.getTransaction().begin();
//        em.getTransaction().commit();
        
	}

	@Override
	public boolean deletePerson(long deadPersonId) {
//		em.getTransaction().begin();
//		Query query = em.createQuery("Delete from Person where id = " + deadPersonId);
//		int results = query.executeUpdate();
//		em.getTransaction().commit();
		em.remove(em.find(Person.class, deadPersonId));
		return true;
	}

	@Override
	public int purgePeople() {
		int results = 0;
		for(Person person : getAllDrivers()) {
			em.remove(person);
			results++;
		}
//			em.getTransaction().begin();	
//		Query query = em.createQuery("Delete from Person");
//		int results = query.executeUpdate();
//		em.getTransaction().commit();
		return results;
		
	}

	@Override
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Override
	public List<Person> getAllDrivers() {
		List<Person> createQuery = em.createQuery("select p from Person p", Person.class).getResultList();
		return createQuery;
	}

	@Override
	public void updatePerson(Person person) {
//		em.getTransaction().begin();
		em.merge(person);
//		em.flush();
//		em.getTransaction().commit();
	}

}
